<template>
  <Modal
    v-model="showImportApiModal"
    title="导入接口"
    :mask-closable="false"
    @on-cancel="handleImportCancel"
  >
    <Form
      inline
      label-position="right"
      :label-width="80"
      :rules="apiImportValidate"
      :model="apiImportForm"
      ref="apiImport"
    >
      <FormItem label="所属项目" prop="project">
        <Select v-model="apiImportForm.project" clearable>
          <Option
            v-for="item in projects"
            :value="item.id"
            :key="item.id"
            :label="item.name"
          />
        </Select>
      </FormItem>
      <FormItem label="文件来源" prop="source">
        <RadioGroup v-model="apiImportForm.source">
          <Radio label="postman"></Radio>
        </RadioGroup>
      </FormItem>
    </Form>
    <Upload
      ref="upload"
      type="drag"
      :before-upload="beforeUpload"
      action="#"
      accept=".json,.har,.yaml,.yml"
      style="margin-top: 10px"
    >
      <div style="padding: 20px 0">
        <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
        <p>
          将文件拖到此处，或
          <label style="color: #3399ff; cursor: pointer">点击此区域</label>
        </p>
      </div>
    </Upload>
    <div v-if="files !== null">
      <div v-for="(item, key) in files" :key="key" style="margin-bottom: 8px">
        <span>{{ item.name }}</span>
        <Button
          type="text"
          @click="remove(item)"
          style="position: absolute; right: 10px; color: #2d8cf0"
        >
          删除
        </Button>
      </div>
    </div>
    <div slot="footer">
      <Button type="default" @click="handleImportCancel">取消</Button>
      <Button
        type="primary"
        :loading="loading"
        @click="handleImportSubmit(false)"
        >导入接口</Button
      >
      <Button
        type="primary"
        :loading="loading"
        @click="handleImportSubmit(true)"
        >导入接口<Divider type="vertical" />生成用例</Button
      >
    </div>
  </Modal>
</template>

<script>
import { getProjectNames } from "@/api/HttpAutoTestService/project";
import { importApiFile } from "@/api/HttpAutoTestService/api";

export default {
  name: "api-import",
  props: {
    importApi: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    showImportApiModal: {
      get() {
        return this.importApi;
      },
      set(val) {
        this.$emit("update:importApi", val);
      },
    },
  },
  watch: {
    importApi(val) {
      if (val) {
        getProjectNames()
          .then((res) => {
            this.projects = res.data;
          })
          .catch((err) => {
            this.$Modal.error({
              title: "系统异常，请联系管理员……",
              content: JSON.stringify(err),
              closable: true,
            });
          });
      }
    },
  },
  data() {
    return {
      loading: false,
      apiImportForm: {
        project: "",
        source: "postman",
      },
      projects: [],
      files: [],
      apiImportValidate: {
        project: [
          { required: true, message: "请选择所属项目", trigger: "change" },
        ],
        source: [
          { required: true, message: "请选择文件来源", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    beforeUpload(file) {
      if (this.files.length === 0) {
        this.files.push(file);
      } else {
        this.$Message.info("仅支持单个文件上传");
      }
      return false;
    },
    remove(file) {
      this.files.pop(file);
    },
    handleImportCancel() {
      this.apiImportForm.project = "";
      this.apiImportForm.source = "postman";
      this.files = [];
      this.loading = false;
      this.showImportApiModal = false;
      this.$emit("initApiTable");
      this.$refs["apiImport"].resetFields();
    },
    handleImportSubmit(create_testcase) {
      this.$refs["apiImport"].validate((valid) => {
        if (valid) {
          if (this.files.length <= 0) {
            this.$Message.error("请选择上传文件");
            return;
          }
          let fd = new FormData();
          this.files.forEach((item) => {
            fd.append("files", item);
          });
          fd.append("project", this.apiImportForm.project);
          fd.append("source", this.apiImportForm.source);
          fd.append("create_testcase", create_testcase);
          this.loading = true;
          importApiFile(fd).then((res) => {
            let result = res.data;
            this.$Message.info(result);
            this.handleImportCancel();
          });
        }
      });
    },
  },
};
</script>

<style scoped>
.ivu-form-item {
  width: 100%;
}
</style>
